package org.jeecg.config.wlhy;


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.constant.enums.BaiduErrorCode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import static org.jeecg.config.wlhy.OkHttp.HTTP_CLIENT;

@Configuration
@Slf4j
public class AipOcrClient {

    @Value("${aip.appId}")
    private String APP_ID;

    @Value("${aip.apiKey}")
    private String API_KEY;

    @Value("${aip.secretKey}")
    private String SECRET_KEY;

    @Value("${aip.proxy.host}")
    private String proxyHost;

    @Value("${aip.proxy.port}")
    private Integer proxyPort;


    @Resource
    StringRedisTemplate stringRedisTemplate;

    public JSONObject businessLicenseUrl(String url) throws IOException {
        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        formBodyBuilder.add("risk_warn", "true");
        formBodyBuilder.add("access_token", getAccessToken());
        formBodyBuilder.add("url", url);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/ocr/v1/business_license")
                .method("POST", formBodyBuilder.build())
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        JSONObject jsonObject = JSONObject.parseObject(response.body().string());
        if (jsonObject.containsKey("error_code")) {
            BaiduErrorCode errorCode = BaiduErrorCode.getInstance(jsonObject.getInteger("error_code"));
            throw new RuntimeException(errorCode.getMessage());
        }
        return jsonObject.getJSONObject("words_result");
    }

    public JSONObject bankcardUrl(String url) throws IOException {
        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        formBodyBuilder.add("access_token", getAccessToken());
        formBodyBuilder.add("url", url);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/ocr/v1/bankcard")
                .method("POST", formBodyBuilder.build())
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        JSONObject jsonObject = JSONObject.parseObject(response.body().string());
        if (jsonObject.containsKey("error_code")) {
            BaiduErrorCode errorCode = BaiduErrorCode.getInstance(jsonObject.getInteger("error_code"));
            throw new RuntimeException(errorCode.getMessage());
        }
        return jsonObject.getJSONObject("result");
    }

    /**
     * 道路运输许可证
     * @param url
     * @return
     * @throws IOException
     */
    public JSONObject roadTransportCertificateUrl(String url) throws IOException {
        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        formBodyBuilder.add("access_token", getAccessToken());
        formBodyBuilder.add("url", url);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/ocr/v1/road_transport_certificate")
                .method("POST", formBodyBuilder.build())
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        JSONObject jsonObject = JSONObject.parseObject(response.body().string());
        if (jsonObject.containsKey("error_code")) {
            BaiduErrorCode errorCode = BaiduErrorCode.getInstance(jsonObject.getInteger("error_code"));
            throw new RuntimeException(errorCode.getMessage());
        }
        return jsonObject.getJSONObject("words_result");
    }
    /**
     * 行驶证识别
     * @param url
     * @param vehicleLicenseSide front/back
     * @return
     * @throws IOException
     */
    public JSONObject vehicleLicenseUrl(String url, String vehicleLicenseSide) throws IOException {
        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        formBodyBuilder.add("access_token", getAccessToken());
        formBodyBuilder.add("url", url);
        formBodyBuilder.add("vehicle_license_side", vehicleLicenseSide);
//        formBodyBuilder.add("quality_warn", "true");
//        formBodyBuilder.add("risk_warn", "true");
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/ocr/v1/vehicle_license")
                .method("POST", formBodyBuilder.build())
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        JSONObject jsonObject = JSONObject.parseObject(response.body().string());
        if (jsonObject.containsKey("error_code")) {
            BaiduErrorCode errorCode = BaiduErrorCode.getInstance(jsonObject.getInteger("error_code"));
            throw new RuntimeException(errorCode.getMessage());
        }
        return jsonObject.getJSONObject("words_result");
    }
    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    String getAccessToken() throws IOException {
        String accessToken = stringRedisTemplate.opsForValue().get("AipOcrToken");
        if (StringUtils.isNotBlank(accessToken)) {
            return accessToken;
        }
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        JSONObject jsonObject = JSONObject.parseObject(response.body().string());
        if (jsonObject.containsKey("error_code")) {
            BaiduErrorCode errorCode = BaiduErrorCode.getInstance(jsonObject.getInteger("error_code"));
            throw new RuntimeException(errorCode.getMessage());
        }

        Long expireIn = jsonObject.getLong("expires_in");
        accessToken = jsonObject.getString("access_token");
        stringRedisTemplate.opsForValue().set("AipOcrToken", accessToken, expireIn, TimeUnit.SECONDS);
        return accessToken;
    }



}
